'use client';

import { useEffect, useState } from 'react';
import { cn } from '@/lib/utils';

interface ScrollProgressProps {
  className?: string;
  height?: number;
  color?: string;
  backgroundColor?: string;
}

/**
 * 页面滚动进度条组件
 * 显示用户在当前页面的滚动进度
 */
export function ScrollProgress({
  className,
  height = 3,
  color = 'bg-blue-600',
  backgroundColor = 'bg-gray-200 dark:bg-gray-800',
}: ScrollProgressProps) {
  const [scrollProgress, setScrollProgress] = useState(0);
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    /**
     * 计算滚动进度百分比
     */
    const calculateScrollProgress = () => {
      const scrollTop =
        window.pageYOffset || document.documentElement.scrollTop;
      const scrollHeight =
        document.documentElement.scrollHeight - window.innerHeight;
      const progress = scrollHeight > 0 ? (scrollTop / scrollHeight) * 100 : 0;

      setScrollProgress(Math.min(100, Math.max(0, progress)));
      setIsVisible(scrollTop > 100); // 滚动超过100px时显示
    };

    /**
     * 节流函数 - 优化性能
     */
    let ticking = false;
    const handleScroll = () => {
      if (!ticking) {
        requestAnimationFrame(() => {
          calculateScrollProgress();
          ticking = false;
        });
        ticking = true;
      }
    };

    // 初始计算
    calculateScrollProgress();

    // 添加滚动监听
    window.addEventListener('scroll', handleScroll, { passive: true });
    window.addEventListener('resize', calculateScrollProgress, {
      passive: true,
    });

    return () => {
      window.removeEventListener('scroll', handleScroll);
      window.removeEventListener('resize', calculateScrollProgress);
    };
  }, []);

  return (
    <div
      className={cn(
        'fixed top-0 left-0 right-0 z-50 transition-opacity duration-300',
        isVisible ? 'opacity-100' : 'opacity-0',
        className
      )}
      style={{ height: `${height}px` }}
    >
      {/* 背景条 */}
      <div className={cn('w-full h-full', backgroundColor)} />

      {/* 进度条 */}
      <div
        className={cn(
          'absolute top-0 left-0 h-full transition-all duration-150 ease-out',
          color
        )}
        style={{
          width: `${scrollProgress}%`,
          transformOrigin: 'left center',
        }}
      />

      {/* 发光效果 */}
      <div
        className={cn(
          'absolute top-0 left-0 h-full opacity-50 blur-sm transition-all duration-150 ease-out',
          color
        )}
        style={{
          width: `${scrollProgress}%`,
          transformOrigin: 'left center',
        }}
      />
    </div>
  );
}

/**
 * 圆形滚动进度指示器
 */
export function CircularScrollProgress({
  className,
  size = 48,
  strokeWidth = 3,
  color = '#3b82f6',
}: {
  className?: string;
  size?: number;
  strokeWidth?: number;
  color?: string;
}) {
  const [scrollProgress, setScrollProgress] = useState(0);
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    const calculateScrollProgress = () => {
      const scrollTop =
        window.pageYOffset || document.documentElement.scrollTop;
      const scrollHeight =
        document.documentElement.scrollHeight - window.innerHeight;
      const progress = scrollHeight > 0 ? (scrollTop / scrollHeight) * 100 : 0;

      setScrollProgress(Math.min(100, Math.max(0, progress)));
      setIsVisible(scrollTop > 200);
    };

    let ticking = false;
    const handleScroll = () => {
      if (!ticking) {
        requestAnimationFrame(() => {
          calculateScrollProgress();
          ticking = false;
        });
        ticking = true;
      }
    };

    calculateScrollProgress();
    window.addEventListener('scroll', handleScroll, { passive: true });
    window.addEventListener('resize', calculateScrollProgress, {
      passive: true,
    });

    return () => {
      window.removeEventListener('scroll', handleScroll);
      window.removeEventListener('resize', calculateScrollProgress);
    };
  }, []);

  const radius = (size - strokeWidth) / 2;
  const circumference = radius * 2 * Math.PI;
  const strokeDasharray = circumference;
  const strokeDashoffset =
    circumference - (scrollProgress / 100) * circumference;

  return (
    <div
      className={cn(
        'fixed bottom-8 right-8 z-50 transition-all duration-300 cursor-pointer',
        isVisible
          ? 'opacity-100 scale-100'
          : 'opacity-0 scale-75 pointer-events-none',
        className
      )}
      onClick={() => {
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }}
      title="返回顶部"
    >
      <div className="relative">
        {/* 背景圆圈 */}
        <svg width={size} height={size} className="transform -rotate-90">
          <circle
            cx={size / 2}
            cy={size / 2}
            r={radius}
            stroke="currentColor"
            strokeWidth={strokeWidth}
            fill="none"
            className="text-gray-200 dark:text-gray-700"
          />

          {/* 进度圆圈 */}
          <circle
            cx={size / 2}
            cy={size / 2}
            r={radius}
            stroke={color}
            strokeWidth={strokeWidth}
            fill="none"
            strokeLinecap="round"
            strokeDasharray={strokeDasharray}
            strokeDashoffset={strokeDashoffset}
            className="transition-all duration-150 ease-out"
          />
        </svg>

        {/* 箭头图标 */}
        <div className="absolute inset-0 flex items-center justify-center">
          <svg
            width={size * 0.4}
            height={size * 0.4}
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth={2}
            strokeLinecap="round"
            strokeLinejoin="round"
            className="text-gray-600 dark:text-gray-300"
          >
            <path d="m18 15-6-6-6 6" />
          </svg>
        </div>
      </div>
    </div>
  );
}

/**
 * 页面章节进度指示器
 */
export function SectionProgress({
  sections,
  className,
}: {
  sections: Array<{ id: string; title: string }>;
  className?: string;
}) {
  const [activeSection, setActiveSection] = useState('');
  const [sectionProgress, setSectionProgress] = useState<
    Record<string, number>
  >({});

  useEffect(() => {
    const observerOptions = {
      root: null,
      rootMargin: '-20% 0px -70% 0px',
      threshold: 0,
    };

    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          setActiveSection(entry.target.id);
        }
      });
    }, observerOptions);

    // 观察所有章节
    sections.forEach(({ id }) => {
      const element = document.getElementById(id);
      if (element) {
        observer.observe(element);
      }
    });

    return () => observer.disconnect();
  }, [sections]);

  return (
    <div
      className={cn(
        'fixed left-8 top-1/2 -translate-y-1/2 z-40 hidden lg:block',
        className
      )}
    >
      <div className="space-y-2">
        {sections.map(({ id, title }) => (
          <div key={id} className="relative group">
            <button
              onClick={() => {
                const element = document.getElementById(id);
                if (element) {
                  element.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start',
                  });
                }
              }}
              className={cn(
                'w-3 h-3 rounded-full border-2 transition-all duration-200',
                activeSection === id
                  ? 'bg-blue-600 border-blue-600 scale-125'
                  : 'bg-transparent border-gray-300 dark:border-gray-600 hover:border-blue-400'
              )}
              title={title}
            />

            {/* 标题提示 */}
            <div className="absolute left-6 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none">
              <div className="bg-gray-900 dark:bg-gray-100 text-white dark:text-gray-900 px-2 py-1 rounded text-sm whitespace-nowrap">
                {title}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
